<template>
  <div class="category-products">
    <h1>{{ categoryName }} 产品列表</h1>
    <div class="product-grid" v-if="products.length">
      <div v-for="product in products" :key="product.id" class="product-card">
        <img :src="product.image" :alt="product.name" />
        <h3>{{ product.name }}</h3>
        <p class="price">¥{{ product.price.toFixed(2) }}</p>
        <button @click="addToCart(product)">加入购物车</button>
      </div>
    </div>
    <p v-else>该分类暂无商品</p>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useProductStore } from '../stores/productStore';
import { useCartStore } from '../stores/cartStore';
const route = useRoute();
const productStore = useProductStore();
const cartStore = useCartStore();
const categoryId = computed(() => parseInt(route.params.id));
const products = ref([]);
const categoryName = ref('');
onMounted(async () => {
  // 修复变量名冲突
  const categoryProducts = productStore.getCategoryProducts(categoryId.value);
  const name = productStore.getCategoryName(categoryId.value);
  
  if (categoryProducts.length === 0) {
    console.warn(`No products found for category ID: ${categoryId.value}`);
  }
  
  products.value = categoryProducts;
  categoryName.value = name || '未知分类';
});
const addToCart = (product) => {
  cartStore.addToCart(product);
  alert('商品已添加到购物车！');
};
</script>
<style scoped>
.category-products {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
h1 {
  font-size: 24px;
  margin-bottom: 20px;
}
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}
.product-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
}
.product-card img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
}
.price {
  font-weight: bold;
  color: #e44d26;
  margin-bottom: 10px;
}
button {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
button:hover {
  background-color: #45a049;
}
</style>
